package assignmentstrategy

import (
	"codejy/analysis/codeanalysis"
	"codejy/globalfunc"
	"codejy/structdef"
	"fmt"
	"strings"
)

func init() {
	globalfunc.RegisterFuncAll("AssignmentStrategyMode", AssignmentStrategyMode)
}

type AssignmentStrategy interface {
	// 策略id
	getId() int
	// 执行策略
	Execute(threadStore *structdef.ThreadStore, code string) string
}

// key策略代号,value策略
var StrategieMap = make(map[int]AssignmentStrategy)

// 注册策略
func RegisterStrategy(strategy AssignmentStrategy) {
	//添加到策略列表
	StrategieMap[strategy.getId()] = strategy
}

// 策略模式(处理表达式内的各种,块代码,函数调用,类型方法调用,字符串处理) ,同时也可以处理函数参数
func AssignmentStrategyMode(threadStore *structdef.ThreadStore, code string) string {
	// 如果是线程地址,那么就直接返回地址
	codeAnalysis := codeanalysis.CodeAnalysis(threadStore, code)
	if codeAnalysis == -1 && strings.HasPrefix(code, "@thread@") {
		return code
	}
	//如果是函数占位符,那么就直接返回空
	if codeAnalysis == -1 && strings.HasPrefix(code, "$") {
		return "\"\""
	}
	// 策略模式,处理各种代码
	strategy, p := StrategieMap[codeAnalysis]
	if !p {
		codeLine := threadStore.Code
		var errorStr = fmt.Sprintf("错误::::::没有找到执行此代码的策略,请检查语法是否正确,类型方法是否定义,变量是否存在,错误代码行: %s,错误代码: %s", codeLine, code)
		panic(errorStr)
	}
	return strategy.Execute(threadStore, code)
}
